package cn.edu.scnu.lastandroid.ui.weather

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.edu.scnu.lastandroid.R
import cn.edu.scnu.lastandroid.logic.model.Weather
import cn.edu.scnu.lastandroid.logic.model.getSky
import java.text.SimpleDateFormat
import java.util.Locale

/*这里也是15.5需要修改的代码，我加入15.6部分*/
class WeatherActivity : AppCompatActivity() {

    val viewModel by lazy { ViewModelProviders.of(this).get(WeatherViewModel::class.java) }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /*下面两个findviewbyid是fozu自己加的，因为下面的swpier和navbtn是15.6需要debug的*/
        val swipeRefresh: SwipeRefreshLayout? = findViewById(R.id.swipeRefresh)
        val navBtn: Button? = findViewById(R.id.navBtn)
        val drawerLayout: DrawerLayout? = findViewById(R.id.drawerLayout)
        if (Build.VERSION.SDK_INT >= 21) {
            val decorView = window.decorView
            decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            window.statusBarColor = Color.TRANSPARENT
        }
        setContentView(R.layout.activity_weather)
        val location_lng=intent.getStringExtra("location_lng")
        Log.d("location_lng", location_lng ?: "101.36")
        if (viewModel.lngStr.isEmpty()) {
            viewModel.lngStr = intent.getStringExtra("location_lng") ?: "101.36"
        }
        if (viewModel.latStr.isEmpty()) {
            viewModel.latStr = intent.getStringExtra("location_lat") ?: "45.31"
        }
        if (viewModel.cityStr.isEmpty()) {
            viewModel.cityStr = intent.getStringExtra("place_name") ?: ""
        }
        viewModel.weatherLiveData.observe(this, Observer { result ->
            val weather = result.getOrNull()
            if (weather != null) {
                showWeatherInfo(weather)
            } else {
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
            swipeRefresh?.isRefreshing = false
        })
        swipeRefresh?.setColorSchemeResources(R.color.colorPrimary)
        refreshWeather()
        swipeRefresh?.setOnRefreshListener {
            refreshWeather()
        }
        navBtn?.setOnClickListener {
            drawerLayout?.openDrawer(GravityCompat.START)
        }
        drawerLayout?.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {}

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {}

            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(
                    drawerView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        })
    }

    /*refreshWeather（）是15.6的内容*/
    fun refreshWeather() {
        val swipeRefresh = findViewById<SwipeRefreshLayout>(R.id.swipeRefresh)
        viewModel.refreshWeather(viewModel.lngStr, viewModel.latStr)
        swipeRefresh.isRefreshing = true
    }

    private fun showWeatherInfo(weather: Weather) {
        val placeName = findViewById<TextView>(R.id.placeName)
        placeName.text = viewModel.cityStr

        //调用model
        val realtime = weather.realtime
        val daily = weather.daily
        val life = weather.life
        val now = weather.now

        // 填充now.xml布局中数据
        val currentTempText = "${realtime.temp.toInt()} ℃"
        val currentTemp = findViewById<TextView>(R.id.currentTemp)
        val currentSky = findViewById<TextView>(R.id.currentSky)
        val currentAQI = findViewById<TextView>(R.id.currentAQI)
        val nowLayout = findViewById<RelativeLayout>(R.id.nowLayout)

        // 填入天气情况和空气指数
        currentTemp.text = currentTempText
        currentSky.text = getSky(realtime.weatherText).info
        val currentPM25Text = "空气指数 ${now.aqi.toInt()}"
        currentAQI.text = currentPM25Text
        nowLayout.setBackgroundResource(getSky(realtime.weatherText).bg)

        // 填充forecast.xml布局中的数据
        val forecastLayout = findViewById<LinearLayout>(R.id.forecastLayout)
        forecastLayout.removeAllViews()
        val days = daily.size
        for (i in 0 until days) {
            val skycon = daily[i].textDay
            val view =
                LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false)
            val dateInfo = view.findViewById(R.id.dateInfo) as TextView
            val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
            val skyInfo = view.findViewById(R.id.skyInfo) as TextView
            val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView
            val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            dateInfo.text = simpleDateFormat.format(daily[i].fxDate)    //读取未来天数的日期
            val sky = getSky(skycon)
            skyIcon.setImageResource(sky.icon)
            skyInfo.text = sky.info

            //温度计算
            val tempText = "${daily[i].tempMin.toInt()} ~ ${daily[i].tempMax.toInt()} ℃"
            temperatureInfo.text = tempText
            forecastLayout.addView(view)
        }

        // 填充life_index.xml布局中的数据
        val lifeIndex = life[0]
        val coldRiskText = findViewById<TextView>(R.id.coldRiskText)
        val dressingText = findViewById<TextView>(R.id.dressingText)
        val ultravioletText = findViewById<TextView>(R.id.ultravioletText)
        val carWashingText = findViewById<TextView>(R.id.carWashingText)
        val weatherLayout = findViewById<ScrollView>(R.id.weatherLayout)

        // 填入生活指数
        coldRiskText.text = lifeIndex.category
        dressingText.text = lifeIndex.category
        ultravioletText.text = lifeIndex.category
        carWashingText.text = lifeIndex.category
        weatherLayout.visibility = View.VISIBLE
    }

}
